<template>
	<view class="content">
		
		<image style="width: 50%;" src="/static/login/dingding.png" mode="widthFix"></image>
		<view class="msg gui-margin-top">
			{{msg}}
		</view>
		<!-- <button @click="dd_login">dd_login</button>
		<view class="gui-margin">
			{{code}}
		</view>
		<button @click="get_user">get_user</button> -->
	</view>
</template>

<script>
	const login = uni.requireNativePlugin('WHY-Login')
	export default {
		data() {
			return {
				code: '',
				msg:'检查是否安装有钉钉..'
			}
		},
		onLoad() {
			let self = this;
			login.isDDAppInstalled(isApp => {
				console.log('----------', isApp) //返回true和false

				if (isApp) {
					self.msg="准备启动钉钉...";
					setTimeout(function() {
						self.dd_login()
					}, 1000)
				}else{
					self.msg="未安装钉钉!";
				}
			})
		},
		methods: {
			dd_login() {
				let self = this;
				login.createDDLogin({
					'appId': 'dingwdjeigxw1fdikjnl',
					'redirectUri': 'https://lg.boyaltd.cn/api/dingding',
					'scope': 'openid',
					'state': 'state',
				}, (res) => {
					console.log('授权结果=========', res)
					
					if (res.code) {
						self.msg="钉钉授权成功,登录中...!";
						self.code = res.code;
						self.get_user(res.code)
					}else{
						self.msg="授权失败:"+res.msg;
					}

					//{"msg":"success","state":0,"code":"*****ccbb2482cb******"}
				})
			},
			get_user(code) {
				let self = this;
				
				console.log("dingding->get_user",code);
				
				
				this.$boya.NPost("/app/dingding_user_info", {
					"code": code
				}, function(res) {
					console.log(res);
					if (res.code == 200) {
						if (res.data) {
							if (res.data.user) {
								self.msg="登录成功!";
								uni.showToast({
									"title": "登录成功",
									"duration": 3000
								})
								self.login_ok(res);
							}
						}
					}else{
						self.msg="登录失败!";
					}

				}, function(err) {
					console.log(err);
				})
			},

			login_ok(res) {
				console.log("login_ok", res);
				uni.setStorageSync("ttsxAuthToken", res.data.ttsxAuthToken);
				uni.setStorageSync("userInfo", res.data.user);
				uni.setStorageSync("token", res.data.token);
				if (res.data.hasOwnProperty("Bearer")) {
					uni.setStorageSync("Bearer", res.data.Bearer);
				}
				console.log("uuid", res.data.uuid);
				uni.setStorageSync("member", res.data.member);
				uni.setStorageSync("platformMall", "c69a70c5-de6f-44fa-a333-88c5a5b3ff77");

				uni.reLaunch({
					url: "/pages/switchPages/main"
				});

			}
		}
	}
</script>

<style>
	.msg{
		font-size: 40rpx;
	}
.content{
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	margin-top: 20%;
}
</style>